<template>
  <div class="data-table">
    <!-- :height="tableHeight" -->
    <div v-if="openSearch" class="detail-btns">
      <ButtonGroup :list="allTabsLists" class="dc-button_group" />
      <div class="dc-search">
        <el-input v-model.trim="fuzzySearch" placeholder="搜索关键词" size="medium" @keyup.enter.native="handleSelectSearch">
          <el-button slot="append" icon="el-icon-search" @click="handleSeacrhBtn" />
        </el-input>
      </div>
    </div>
    <el-table
      ref="componentsTable"
      v-loading="loading"
      :data="tableData"
      :max-height="maxHeight"
      style="width: 100%"
      :border="border"
      @selection-change="handleSelectionChange"
      @select-all="handleSelectAll"
      @row-click="jumpDetails"
      @sort-change="changeTabSort"
    >
      <template v-for="(col, index) in columns_data">
        <!-- 操作列/自定义列 -->
        <slot v-if="col.slot" :name="col.slot">
          <el-table-column v-if="col.slot === 'index'" type="index" :index="indexFun" width="60" label="序号" align="center" />
        </slot>
        <!-- 普通列 :width="col.width"-->
        <el-table-column
          v-else
          :key="col.key + '' + index"
          :column-key="col.key"
          :prop="col.prop"
          :label="col.label"
          :min-width="col.width"
          align="center"
          :fixed="col.fixed"
          :sortable="col.sortable"
          show-overflow-tooltip
        >
          <template slot="header" slot-scope="scope">
            <template v-if="headSearch">
              <el-popover-container v-if="col.type === 'search'" :col="col" @handleSearch="handleSearch" @handleReset="handleReset">
                <!-- 输入框 查询 -->
                <el-input
                  v-model="watchParams[scope.column.property]"
                  suffix-icon="el-icon-search"
                  size="medium"
                  clearable
                  style="line-height: 24px"
                  placeholder="search"
                  @clear="handleSearch"
                  @keyup.enter.native="handleSearch"
                />
              </el-popover-container>
              <template v-if="col.type === 'radio'">
                <el-popover-radio v-model="watchParams[scope.column.property]" :col="col" :isparams="col.isparams" @changeSearch="handleSearch" />
              </template>
              <template v-if="col.type === 'select'">
                <el-popover-select
                  v-if="col.min === 0 && col.max === 1"
                  v-model="watchParams[scope.column.property]"
                  :col="col"
                  :isparams="col.isparams"
                  @changeSearch="handleSearch"
                />
                <el-popover-container v-else :col="col" @handleSearch="handleSearch">
                  <!-- 静态数据 select -->
                  <Select
                    ref="selectBox"
                    v-model="watchParams[scope.column.property]"
                    :lists="col.select"
                    :key-label="col.selectLabel"
                    :key-value="col.selectValue"
                    :select-remote="col.selectRemote"
                    :select-options="col.selectOptions"
                    :multiple="col.multiple"
                    :min="col.min"
                    :max="col.max"
                    @changeSearch="handleSearch"
                  />
                </el-popover-container>
              </template>
              <el-popover-cascader
                v-if="col.type === 'cascader'"
                v-model="watchParams[col.value || scope.column.property]"
                :row-key="col.value || scope.column.property"
                :col="col"
                @changeSearch="changeCascader"
              />
              <el-popover-container v-if="col.type === 'date-link'" :col="col" @handleSearch="handleSearch">
                <div style="display: flex; justify-content: space-between">
                  <el-date-picker v-model="watchParams['startTime']" type="date" value-format="yyyy-MM-dd 00:00:00" placeholder="选择日期" :style="{ width: '43%' }" />
                  <span style="color: #999; margin: 0 2px; font-size: 12px; line-height: 36px">至</span>
                  <el-date-picker v-model="watchParams['endTime']" type="date" value-format="yyyy-MM-dd 23:59:59" placeholder="选择日期" :style="{ width: '43%' }" />
                </div>
              </el-popover-container>
            </template>

            <span v-if="!['search', 'select', 'cascader', 'date-link', 'radio'].includes(col.type) || !headSearch">{{ col.label }}</span>
          </template>
        </el-table-column>
      </template>
      <div slot="empty">
        <slot name="empty">
          <el-empty description="暂无数据" />
        </slot>
      </div>
    </el-table>
    <!-- 是否调用分页 -->
    <div class="clearfix" style="text-align: right;">
      <el-pagination
        v-if="isPagination"
        style="overflow: hidden"
        background
        layout="slot, total, sizes, prev, pager, next"
        :current-page.sync="pageNum"
        :page-size.sync="pageSize"
        :page-sizes="[10, 15, 20, 25, 30]"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>
<script>
// import debounce from 'lodash/debounce'
import request from '@/utils/request.js'
// 选择相关
import selectMixin from './mixin/select.js'
import deitailSearchMixin from './mixin/deitailSearch.js'
// 列表接口请求
// import apiMixin from './mixin/api.js'
import ButtonGroup from '@/components/Common/buttonGroup/index.vue'
import { ElPopoverSelect, ElPopoverContainer, ElPopoverCascader, ElPopoverRadio } from './components/index'
export default {
  name: 'TabtableList',
  components: {
    // Cascader,
    ElPopoverSelect,
    ElPopoverContainer,
    ElPopoverCascader,
    ElPopoverRadio,
    ButtonGroup
  },
  mixins: [selectMixin, deitailSearchMixin],
  props: {
    /**
     * 表格列配置
     * [{
     * label: '用户名', // 列名称
     * prop: 'userName', // 列显示字段
     * width: '90', // 列宽度初始值
     * }]
     */
    columns: {
      type: Array,
      required: true,
      default() {
        return []
      }
    },
    data: {
      type: Array,
      default() {
        return []
      }
    },
    /**
     * 接口传参配置
     */
    params: {
      type: Object,
      default() {
        return {}
      }
    },
    // 列表请求路径
    url: {
      type: String,
      default: ''
    },
    returnData: {
      type: [Function, String],
      default: ''
    },
    // 是否分页
    isPagination: {
      type: Boolean,
      default: true
    },
    pramsWatch: {
      type: Boolean,
      default: false
    },
    headSearch: {
      type: Boolean,
      default: false
    },
    methodType: {
      type: String,
      default: 'get'
    },
    maxHeight: {
      type: String || Number,
      default: null
    },
    border: {
      type: Boolean,
      default: true
    },

  },
  data() {
    return {
      columns_data: [],
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      // 已选择数据
      selectionData: [],
      originalParams: {},
      watchParams: {},
      sortParams: {},
      searchText: '',
      fuzzySearch: '', // 复合模糊查询参数
    }
  },
  watch: {
    data: {
      handler(v) {
        this.tableData = v
      },
      immediate: true
    },
    columns: {
      handler(v) {
        this.columns_data = this.$_.cloneDeep(v).map((c, index) => {
          c.key = new Date().getTime() + ((Math.random() * 1000).toFixed(0) + index)
          return c
        })
      },
      deep: true,
      immediate: true
    },
    params: {
      handler(v) {
        this.watchParams = JSON.parse(JSON.stringify(v))
        this.originalParams = JSON.parse(JSON.stringify(v))
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    indexFun(index) {
      return index + this.pageSize * (this.pageNum - 1) + 1
    },
    // 单页个数
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },
    // 跳页
    handleCurrentChange(val) {
      this.pageNum = val
      this.getList()
    },
    setParamsBefore() {
      var t = {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        ...this.watchParams,
        ...this.sortParams
      }
      return t
    },
    changeTabSort(column, prop, v) {
      if (column.order) {
        var order = column.order === 'descending' ? 'desc' : 'asc'
        this.sortParams = {
          sortName: column.prop.replace(/([A-Z])/g, '_$1').toLowerCase(),
          sortOrder: order
        }
      } else {
        this.sortParams = {}
      }

      this.pageNum = 1
      this.getList()
    },
    // 列表查询
    getList() {
      if (!this.url) return
      this.loading = true
      this._request(this.setParamsBefore())
        .then(r => {
          var res = r.data
          if (typeof this.returnData === 'function') {
            this.tableData = this.returnData(res)
          } else {
            this.tableData = res.data.list
          }
          this.total = res.total
          if (this.selectionConfig.rowBoolean) {
            this.diffSelect = []
            this.toggleRowForEarch(this.selectionData)
          }

          this.$refs.componentsTable.doLayout()
          this.loading = false
        })
        .catch(e => {
          this.tableData = []
          this.loading = false
        })
    },
    _request(data) {
      if (this.methodType === 'post') {
        return request.post(this.url, data)
      } else {
        return request.get(this.url, { params: data })
      }
    },
    jumpDetails(row, column) {
      if (column.type === 'selection') {
        const componentsTable = this.$refs.componentsTable
        // selection 存在时，selection 的 selectable 返回结果为 true 时，才能选中
        // selection 不存在时，直接选中
        const selection = componentsTable.columns.find(x => x.type === 'selection')
        if (selection && selection.selectable && typeof selection.selectable === 'function') {
          if (selection.selectable(this.tableData[row.sf_index])) {
            return componentsTable.toggleRowSelection(this.tableData[row.sf_index])
          }
        } else if (!selection) {
          return componentsTable.toggleRowSelection(this.tableData[row.sf_index])
        }
        return
      }
      if (column.label && column.label === '操作') {
        return
      }
      this.$emit('jumpDetails', row, column)
    },
    handleSearch() {
      this.pageNum = 1
      this.getList()
    },
    handleSearchParams(v) {
      this.watchParams = v
      this.pageNum = 1
      this.getList()
    },
    handleReset() {
      this.watchParams = JSON.parse(JSON.stringify(this.originalParams))
      this.pageNum = 1
      this.getList()
    },
  }
}
</script>
